package com.rlyy.basic.resolver.valid;

import com.rlyy.common.exception.ParameterValidException;
import com.rlyy.common.param.RequestWrapper;
import com.rlyy.basic.resolver.valid.check.ValidatorFactoryUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.method.HandlerMethod;

import javax.validation.groups.Default;
import java.util.Collection;
import java.util.Map;

/**
 * @author : shibixiao
 * @description :
 * @date : 2021-03-22 15:27
 **/
@Component
public class EntityValidatorProcessor implements IMyValidatedPostProcessor {


    @Autowired
    private ValidatorFactoryUtils validatorFactoryUtils;

    @Override
    public boolean supportsValid(RequestWrapper requestWrapper) {
        HandlerMethod handlerMethod = requestWrapper.getHandlerMethod();
        MethodParameter[] methodParameters = handlerMethod.getMethodParameters();
        if (methodParameters.length != 1) {
            return false;
        }
        MethodParameter methodParameter = methodParameters[0];
        boolean isEntity = this.isEntity(methodParameter.getParameterType());
        return methodParameter.getParameterAnnotation(Validated.class) != null && isEntity;
    }


    @Override
    public void validate(RequestWrapper requestWrapper) throws ParameterValidException {
        HandlerMethod handlerMethod = requestWrapper.getHandlerMethod();
        MethodParameter[] methodParameters = handlerMethod.getMethodParameters();
        Class<?>[] groups = methodParameters[0].getParameter().getAnnotation(Validated.class).value();
        groups = ObjectUtils.isEmpty(groups) ? new Class<?>[]{Default.class} : groups;
        boolean enableFastFail = this.enableFastFail(handlerMethod);
        String failValidator = validatorFactoryUtils.validator(requestWrapper.getRequestParams()[0],enableFastFail, groups);
        if (!StringUtils.isEmpty(failValidator)) {
            throw new ParameterValidException(failValidator);
        }
    }


    /**
     * 判断参数类型是实体类
     *
     * @param parameterType 参数类型
     * @return true or false
     */
    private boolean isEntity(Class<?> parameterType) {
        boolean isNotCollection = !Collection.class.isAssignableFrom(parameterType);
        boolean isNotMap = !Map.class.isAssignableFrom(parameterType);
        return !BeanUtils.isSimpleProperty(parameterType) && isNotCollection && isNotMap;
    }



}
